import pandas as pd
import os
import sys


class OdooModel():

    columns = []
    package = ''
    model_name = ''
    description = ''
    model_file = ''
    path = './'
    addone_name = 'temp'
    manifest_fmt = {
        'title': '',
        'version': '',
        'name': '',
        'description': '',
        'author': '',
        'category': "",
        'depends': ['base'],
        'application': True,
        'data': [
            'security/ir.model.access.csv',

        ],
    }
    addone_init_fmt = "from . import models \n"
    model_init_fmt = "# -*- coding: utf-8 -*- \n"
    access_fmt = "id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink"

    def __init__(self, addone_name, model_file) -> None:
        self.addone_name = addone_name
        self.model_file = model_file

        sub_path_arr = ['models', 'security',
                        'static', 'views', 'static/description']
        # path
        for sub_path in sub_path_arr:
            sub_path_full = '{}/{}/{}'.format(self.path,
                                              self.addone_name, sub_path)
            if not os.path.exists(sub_path_full):
                os.makedirs(sub_path_full)
                print('路径:', sub_path_full, '创建完成')
            else:
                print('路径:', sub_path_full, '已存在')
        # manifest_fmt.py
        self.write_file('{}/{}/{}.py'.format(self.path,
                        self.addone_name, "__manifest__"), str(self.manifest_fmt))
        # addone_init_fmt __init__.py
        self.write_file('{}/{}/{}.py'.format(self.path,
                        self.addone_name, "__init__"), self.addone_init_fmt)
        # model_init_fmt __init__.py
        self.write_file('{}/{}/{}/{}.py'.format(self.path, self.addone_name,
                        sub_path_arr[0], "__init__"), self.model_init_fmt)
        # access_fmt __init__.py
        self.write_file('{}/{}/{}/{}.csv'.format(self.path, self.addone_name,
                        sub_path_arr[1], "ir.model.access"), self.access_fmt)

    def set_default(self, model_file) -> None:
        self.model_file = model_file

    def write_file(self, file_path, text):
        with open(file_path, 'w+') as f:
            f.write(text)
        print('创建:', file_path, '成功!')
        return True

    def read_file(self, file_path):
        content = ''
        with open(file_path, 'r') as f:
            content = f.read()
        return content

    def add_line(self, file_path, add_line):
        content = ''
        with open(file_path, 'r') as f:
            content = f.read()
        content += (add_line)
        with open(file_path, 'w+') as f:
            f.write(content)

    def read_format(self):
        model_fmt = """
from odoo import api, fields, models
from odoo.exceptions import UserError
import logging
_logger = logging.getLogger(__name__)

class {name}(models.Model):
    # properties
    _name = '{package}.{name}'
    _inherit = ['mail.thread']
    _description = '{description}'
    # String fields
    {fields}
"""
        view_fmt = """<?xml version="1.0"?>
<odoo>

	<record id="view_list_{package}_{name}" model="ir.ui.view">
		<field name="name">{package}_{name} List</field>
		<field name="model">{package}.{name}</field>
		<field name="arch" type="xml">
			<tree string="{package}_{name} List">
				{field}
			</tree>
		</field>
	</record>
	<record id="view_form_{package}_{name}" model="ir.ui.view">
		<field name="name">{package}_{name} Form</field>
		<field name="model">{package}.{name}</field>
		<field name="arch" type="xml">
			<form string="{package}_{name} Form" class="o_form_project_tasks" js_class="project_task_form">
				<!-- <header>
					<button name="" string="" type="object" class="oe_highlight"/>
				</header> -->
				<sheet>
					<!-- <div class="oe_title pr-0">
						<h1 class="d-flex flex-row justify-content-between">
							<field name="name"/>
						</h1>
					</div> -->
					<group>
						{field}
					</group>

					<notebook>
						<!-- <page name="" string="">
							<field name=""/>
						</page> -->

					</notebook>
				</sheet>
                <div class="oe_chatter">
					<field name="message_follower_ids" widget="mail_followers"/>
					<field name="message_ids" widget="mail_thread"/>
				</div>
			</form>
		</field>
	</record>

	<record id="{package}_{name}_list_action" model="ir.actions.act_window">
		<field name="name">{description}</field>
		<field name="type">ir.actions.act_window</field>
		<field name="res_model">{package}.{name}</field>
		<field name="view_mode">tree,form,pivot</field>
	</record>


	<menuitem action="{package}_{name}_list_action" id='{package}_{name}_list' name="{description}" parent="" sequence="100"/>


</odoo>
"""

        access_fmt = """
access_{name},access_{name},model_{package}_{name},base.group_user,1,1,1,1"""
        return model_fmt, view_fmt, access_fmt

    def create_col(self, columns):
        feild_model_fmt = "{name} = fields.{type}({many}string='{show_name}')"
        feild_view_fmt = "<field name='{name}'/>"
        feild_model_arr = []
        feild_view_arr = []
        
        print("name", "type", "description")
        for item in columns:
            fmt_many_str = ''
            print(item['name'], item['type'], item['description'])
            if item['type'] == 'Many2many' or item['type'] == 'Many2one':
                fmt_many_str = "'{package}.{table}',".format(package=self.package, table=item['table'])
            if item['type'] == 'One2many':
                fmt_many_str = "'{package}.{table}','{column}',".format(package=self.package,table=item['table'], column=item['column'])
            feild_model_fmt_str = feild_model_fmt.format(
                name=item['name'], type=item['type'], show_name=item['description'], many=fmt_many_str)
            feild_model_arr.append(feild_model_fmt_str)
            feild_view_arr.append(feild_view_fmt.format(name=item['name']))

        feild_model_txt = '\n    '.join(feild_model_arr)
        feild_view_txt = '\n				'.join(feild_view_arr)
        return feild_model_txt, feild_view_txt

    def save2file(self):

        model_fmt, view_fmt, access_fmt = self.read_format()
        df0 = pd.read_excel(self.model_file, sheet_name='list')

        for item in df0.to_records('record'):
            print('------------start------------')
            self.package = item['package']
            self.model_name = item['name']
            self.description = item['description']

            print('package:', self.package)
            print('name:', self.model_name)
            print('description:', self.description)
            print('Author:', item['author'])
            print('Date:', item['date'])
            print('----Columns-----')
            df1 = pd.read_excel(self.model_file, sheet_name=self.model_name)
            columns = df1.to_records('record')

            feild_model_txt, feild_view_txt = self.create_col(columns)
            print('-----Files----')

            # model write
            model_txt = model_fmt.format(
                package=self.package, name=self.model_name, description=self.description, fields=feild_model_txt)
            file_path = '{path}/{addone}/models/{package}_{name}.py'.format(
                path=self.path, addone=self.addone_name, package=self.package, name=self.model_name)

            self.write_file(file_path, model_txt)
            print(file_path)
            # view write
            view_txt = view_fmt.format(
                package=self.package, name=self.model_name, description=self.description, field=feild_view_txt)
            file_path = '{path}/{addone}/views/{package}_{name}.xml'.format(
                path=self.path, addone=self.addone_name, package=self.package, name=self.model_name)
            self.write_file(file_path, view_txt)
            print(file_path)
            # access
            file_path = '{path}/{addone}/security/ir.model.access_{name}.csv'.format(
                path=self.path, addone=self.addone_name, name=self.model_name)
            access_txt = access_fmt.format(
                package=self.package, name=self.model_name)
            # self.write_file(file_path,access_txt)
            self.add_line('{}/{}/models/__init__.py'.format(self.path, self.addone_name),
                          'from . import {package}_{name} \n'.format(package=self.package, name=self.model_name))
            self.add_line(
                '{}/{}/security/ir.model.access.csv'.format(self.path, self.addone_name), access_txt)
            # manifest_fmt.py
            view_file_path = 'views/{package}_{name}.xml'.format(package=self.package, name=self.model_name)
            self.manifest_fmt['data'].append(view_file_path)
            self.write_file('{}/{}/__manifest__.py'.format(self.path,self.addone_name), str(self.manifest_fmt))
            print(file_path)
            print(str(self.manifest_fmt))
            print('------------End------------')
            print('代码生成完毕,请手动创建链接')


if __name__ == "__main__":
    print('参数:', sys.argv)
    om = OdooModel(addone_name=sys.argv[1], model_file=sys.argv[2])
    om.save2file()

